<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="primary" icon="el-icon-refresh" @click="handleRefresh">
        刷新
      </el-button>
      <el-input v-model="listQuery.searchMsg" placeholder="搜索内容" style="width: 200px;" class="filter-item filter-input"
                @keyup.enter.native="handleFilter"/>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item add" style="margin-left: 10px;" type="primary" icon="el-icon-circle-plus-outline"
                 @click="handleCreate">
        添加
      </el-button>

    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row

    >
      <el-table-column
        type="index"
        label="序号"
        align="center"
        width="50">
      </el-table-column>
      <!-- <el-table-column align="center" label="ID" width="95" >
        <template slot-scope="scope">
          {{ scope.row.Index }}
        </template>
      </el-table-column> -->

      <el-table-column label="名称" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="默认值" prop="adminRoles" align="center">
        <template slot-scope="scope">
          {{ truncatedText(scope.row.value) }}


        </template>
      </el-table-column>
      <el-table-column label="类型" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.valueType }}
        </template>
      </el-table-column>
      <!--<el-table-column class-name="status-col" label="状态" width="110" align="center">-->
      <!--<template slot-scope="scope">-->
      <!--<el-switch-->
      <!--v-model="scope.row.status"-->
      <!--active-color="#13ce66"-->
      <!--@change="handleStatus(scope.row)"-->
      <!--&gt;-->
      <!--</el-switch>-->

      <!--&lt;!&ndash; <el-tag :type="scope.row.status | statusFilter">{{ scope.row.status }}</el-tag> &ndash;&gt;-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column align="center" prop="created_at" label="创建时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time"/>
          <span>{{ scope.row.createdAt }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" prop="updated_at" label="更新时间" width="200">
        <template slot-scope="scope">
          <i class="el-icon-time"/>
          <span>{{ scope.row.updatedAt }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
                @pagination="fetchData"/>

    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="Form" label-position="left" label-width="90px"
               style="width: 400px; margin-left:50px;">

        <el-form-item label="名称" prop="name">
          <el-input v-model="Form.name"/>
        </el-form-item>
        <el-form-item label="值类型" prop="valueType">
          <el-select v-model="Form.valueType" placeholder="请选择">
            <el-option
              v-for="item in parsedOptions(valueTypeList)"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="默认值">
          <el-input v-model="Form.value"/>
        </el-form-item>


      </el-form>
      <h2>
        提示: 类型为单选或者多选的默认值，需使用英文“,”号进行分隔。

      </h2>
      <h2>
        示例: 值1,值2,值3
      </h2>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination

  import {IgsConfigAPI} from '../../../../api/igs/igsConfig'

  export default {
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'gray',
          deleted: 'danger'
        }
        return statusMap[status]
      }
    },
    components: {Pagination},
    name: 'user',
    data() {
      const validatePassword = (rule, value, callback) => {

        if (value.length < 6) {
          callback(new Error('密码长度不能低于6位'))
        } else {
          callback()
        }
      }

      const validateUser = (rule, value, callback) => {
        let reg = /^[a-zA-Z0-9]+$/;
        if (value === '') {
          callback(new Error('用户名不能为空'))
        } else if (!reg.test(value)) {
          callback(new Error('用户名只能输入英文字母及数字'))

        } else {
          callback()
        }
      }
      return {
        list: null,
        listLoading: true,
        total: 0,
        listQuery: {
          page: 1,
          limit: 10,
          searchMsg: '',
          orderby: 'ORDER BY `id` DESC'
        },
        dialogFormVisible: false,
        dialogStatus: "create",
        title: "",
        rules: {
          name: [
            {required: true, message: '请输入名称', trigger: 'blur'}
          ],
          valueType: [
            {required: true, message: '请选择值类型', trigger: 'blur'}
          ],
          username: [
            {required: true, validator: validateUser, trigger: 'blur'}
          ],


        },
        Form: {
          id: null,
          name: "",
          value: "",
          valueType: '',
          baseType: 0,//0为基础，1为病人通用

        },
        valueTypeList: '文本,数字,时间,日期,单选,多选',
      }
    },
    created() {
      this.fetchData()
    },
    methods: {
      //单选框，多选
      parsedOptions(list) {


        return list.split(',').map(value => ({
          value: value,
          label: value
        }));


      },
      truncatedText(longText) {
        console.log('in to truncatedText:', longText);
        if (longText == null) {
          return ''
        }
        return longText.length > 30 ? longText.slice(0, 30) + '...' : longText;
      },
      fetchData() {
        this.listLoading = true
        IgsConfigAPI.hasAllToPage(this.listQuery).then(response => {
          let list = response.data.list

          const data = list
          this.list = data
          this.total = response.data.queryTotal
          this.listQuery.page = response.data.page
          setTimeout(() => {
            this.listLoading = false
          }, 0.3 * 1000)
        })

      },
      getList() {
        this.listLoading = true
        IgsConfigAPI.hasAllToPage(this.listQuery).then(response => {
          let list = response.data.list

          const data = list
          this.list = data
          this.total = response.data.queryTotal
          this.listQuery.page = response.data.page
          setTimeout(() => {
            this.listLoading = false
          }, 0.3 * 1000)
        })
      },
      handleFilter() {
        //搜索
        this.listQuery.page = 1
        this.listQuery.searchMsg = this.listQuery.searchMsg.trim()
        this.fetchData()
      },
      handleCreate() {
        //新增
        this.dialogFormVisible = true
        this.title = "添加"
        this.dialogStatus = 'create'
        this.Form = {
          id: null,
          name: "",
          value: "",
          valueType: '',
          baseType: 0

        }
        setTimeout(() => {
          this.$refs['dataForm'].clearValidate();
        }, 300)
      },
      handleUpdate(row) {
        //编辑
        this.dialogFormVisible = true
        this.title = "修改"
        this.dialogStatus = 'update'
        this.Form = {
          id: row.id,
          name: row.name,
          value:row.value,
          valueType:row.valueType,
          baseType:0

        }
        console.log(row)
        console.log(this.Form)
      },
      handleDelete(row, index) {
        //删除
        this.$confirm('确认删除？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          IgsConfigAPI.delete({id: row.id}).then(() => {
            this.$notify({
              title: 'Success',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
          })
        }).catch(() => {
        });
      },
      handleRefresh() {
        //列表刷新
        this.fetchData()
      },
      handleStatus(row) {
        //更改状态
        console.log(row)
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            IgsConfigAPI.add(this.Form).then((response) => {
              this.fetchData()
              this.dialogFormVisible = false
            })
          }
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            IgsConfigAPI.update(this.Form).then(() => {
              this.fetchData()
              this.dialogFormVisible = false
            })

          }
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .filter-container {
    .filter-item {
      margin-bottom: 10px;
    }
    .filter-input {
      margin-left: 20px;
    }
    .add {
      float: right;
    }
  }
</style>
